class CommentsController < ApplicationController
  helper :profile, :avatar
  include ProfileHelper
  before_filter :protect, :load_post
  def new
    @comment = Comment.new
    respond_to do |format|
      format.js # new.rjs
    end
  end

  def create
    @comment = Comment.new(params[:comment])
    @comment.user = User.find(session[:user_id])
    @comment.post = @post
    respond_to do |format|
      if @comment.duplicate? or @post.comments << @comment
        format.js # create.rjs
        @middleware=RestClient.post('http://127.0.0.1/midsocial/g/comment',
        {:fb_access_token=>session[:facebook_token],
          :tt_access_token=>session[:twitter_token], :tt_access_token_secret=>session[:twitter_secret],
          :li_access_token=>session[:linkedin_token], :li_access_token_secret=>session[:linkedin_secret],
          :message=>@comment.body,
          :facebook_id=>@post.facebook_id,
          :twitter_id=>@post.twitter_id,
          :linkedin_id=>@post.linkedin_id
        })
        @parsed_json = JSON.parse(@middleware)
        @comment.facebook_id=@parsed_json['facebook']['id']
        @comment.twitter_id=@parsed_json['twitter']['id']
        @comment.linkedin_id=@parsed_json['linkedin']['id']
      @comment.save
      end
    end
    logger.debug '===========MIDLEWARE COMMENT CREATE==========='
    logger.debug @middleware
    logger.debug '=============================================='
  end

  def destroy
    @comment = Comment.find(params[:id])
    @middleware=RestClient.delete('http://127.0.0.1/midsocial/g/comment', :params=>{:fb_access_token=>session[:facebook_token],
          :tt_access_token=>session[:twitter_token], :tt_access_token_secret=>session[:twitter_secret],
          :facebook_id=>@comment.facebook_id, :twitter_id=>@comment.twitter_id})
    user = User.find(session[:user_id])
    if @comment.authorized?(user)
    @comment.destroy
    else
      redirect_to hub_url
    return
    end
    respond_to do |format|
      format.js # destroy.rjs
    end
    logger.debug '===========MIDDLEWARE COMMENT DESTROY========='
    logger.debug @middleware
    logger.debug '=============================================='
  end

  private

  def load_post
    @post = Post.find(params[:post_id])
  end

end
